package com.springboot.cloud.demos.producer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.cloud.demos.entity.param.MomentSupportQueryParam;
import com.springboot.cloud.demos.entity.po.MomentSupport;
import com.springboot.cloud.demos.producer.dao.MomentSupportMapper;
import com.springboot.cloud.demos.producer.service.IMomentSupportService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
@Slf4j
@RefreshScope
public class MomentSupportServiceImpl extends ServiceImpl<MomentSupportMapper, MomentSupport> implements IMomentSupportService {

    @Value("${producer.momentSupport:123}")
    private String value;

    @Override
    @CacheEvict(value = "MomentSupport", allEntries = true)
    public boolean add(MomentSupport momentSupport) {
       MomentSupport momentSupport1= this.queryByUser(momentSupport.getUserId(),momentSupport.getType(),momentSupport.getMomentId());
       if(momentSupport1!=null){
           return false;
       }
        return this.save(momentSupport);

    }


    @Override
    @CacheEvict(value = "MomentSupport", allEntries = true)
    public boolean delete(String id) {
        return this.removeById(id);
    }

    @Override
    public List<Map<String,Object>> querySignUpList(String momentId) {
        return getBaseMapper().getSignUpList(momentId);
    }

    @Override
    public boolean update(MomentSupport momentSupport) {
        return this.updateById(momentSupport);
    }

    @Override
    public MomentSupport get(String id) {
        log.info("value:{}", value);
        return this.getById(id);
    }


    @Override
    @Cacheable(value = "MomentSupport", key = "#root.targetClass+'-'+#userId+'-'+#type+'-'+#momentId")
    public MomentSupport queryByUser(String userId,Integer type, String momentId) {
        QueryWrapper<MomentSupport> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("moment_id", momentId);
        queryWrapper.eq("type",type);
        List<MomentSupport> list = this.list(queryWrapper);
        if (list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public List<MomentSupport> query(MomentSupportQueryParam param) {
        QueryWrapper<MomentSupport> queryWrapper = param.build();
        queryWrapper.eq("user_id", param.getUserId());
        queryWrapper.eq("moment_id", param.getLessonId());
        queryWrapper.eq("type", param.getType());
        return this.list(queryWrapper);
    }

}
